<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useAnalysisStore } from '@/stores/analysisStore'

const props = defineProps({
  city: {
    type: String,
    required: true
  }
})

const analysisStore = useAnalysisStore()
const chartContainer = ref(null)
let chart = null
const loading = ref(false)

const initChart = () => {
  if (!chartContainer.value) return
  
  chart = echarts.init(chartContainer.value)
  chart.showLoading()
}

const loadData = async () => {
  if (!props.city) return
  
  loading.value = true
  try {
    const data = await analysisStore.fetchPriceAreaScatter(props.city)
    renderChart(data)
  } catch (error) {
    console.error('加载价格-面积散点图数据失败:', error)
  } finally {
    loading.value = false
    if (chart) {
      chart.hideLoading()
    }
  }
}

const renderChart = (data) => {
  if (!chart) return
  
  // 计算回归线
  const calculateRegressionLine = (data) => {
    const n = data.length
    let sumX = 0
    let sumY = 0
    let sumXY = 0
    let sumX2 = 0
    
    data.forEach(point => {
      sumX += point[0]
      sumY += point[1]
      sumXY += point[0] * point[1]
      sumX2 += point[0] * point[0]
    })
    
    const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX)
    const intercept = (sumY - slope * sumX) / n
    
    // 生成回归线的点
    const minX = Math.min(...data.map(point => point[0]))
    const maxX = Math.max(...data.map(point => point[0]))
    
    return [
      [minX, slope * minX + intercept],
      [maxX, slope * maxX + intercept]
    ]
  }
  
  // 转换数据格式
  const scatterData = data.points.map(point => [point.area, point.price])
  const regressionLine = calculateRegressionLine(scatterData)
  
  const option = {
    title: {
      text: `${props.city}房价与面积关系`,
      left: 'center',
      textStyle: {
        fontSize: 16
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      containLabel: true
    },
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        if (params.seriesIndex === 0) {
          return `面积: ${params.value[0]} 平方米<br/>价格: ${params.value[1]} 元/平方米`
        }
        return ''
      }
    },
    xAxis: {
      type: 'value',
      name: '面积 (平方米)',
      nameLocation: 'middle',
      nameGap: 30,
      axisLine: {
        show: true
      },
      axisTick: {
        show: true
      }
    },
    yAxis: {
      type: 'value',
      name: '价格 (元/平方米)',
      nameLocation: 'middle',
      nameGap: 40,
      axisLine: {
        show: true
      },
      axisTick: {
        show: true
      }
    },
    series: [
      {
        name: '房源',
        type: 'scatter',
        symbolSize: 8,
        itemStyle: {
          color: '#5470c6',
          opacity: 0.7
        },
        data: scatterData
      },
      {
        name: '趋势线',
        type: 'line',
        showSymbol: false,
        data: regressionLine,
        lineStyle: {
          color: '#ee6666',
          width: 2
        }
      }
    ]
  }
  
  chart.setOption(option)
}

const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

watch(() => props.city, () => {
  loadData()
})

onMounted(() => {
  initChart()
  loadData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 